package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.CheckGroupDao;
import com.itheima.dao.CheckItemDao;
import com.itheima.dao.CheckSetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CheckGroupService;
import com.itheima.service.CheckSetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckSetmealService.class)
//涉及多表，使用事务管理
@Transactional
public class CheckSetmealServiceImpl implements CheckSetmealService {
    @Autowired
    private CheckSetmealDao checkSetmealDao;
    @Autowired
    private CheckGroupDao checkGroupDao;
    @Autowired
    private CheckItemDao checkItemDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    //@Value("${out_put_path}")
    private  String outputpath ="D:\\Code\\itcast_health\\health_parent\\health_mobile\\src\\main\\webapp\\pages";//  从属性中获取要生成html的路径

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return checkSetmealDao.findSetmealCount();
    }

    @Override
    public void add(Setmeal setmeal, Integer[] checkitemIds) {
        checkSetmealDao.add(setmeal);
        addGroupAndItem(setmeal.getId(),checkitemIds);
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        //生成当前方法所需的静态页面（套餐列表，套餐详情）
        generateMobileStaticHtml();

    }

    //生成静态页面
    public void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = this.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }

    //生成套餐详情静态页面（多个）
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("setmeal", this.findById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl",
                    "setmeal_detail_"+setmeal.getId()+".html",
                    dataMap);
        }
    }

    //生成套餐列表静态页面
    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",dataMap);
    }

    //通用方法，用于生成静态页面
    private void generateHtml(String templateName,String htmlPageName,Map<String, Object> dataMap){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            // 加载模版文件
            Template template = configuration.getTemplate(templateName);
            // 生成数据
            File docFile = new File(outputpath + "\\" + htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile),"utf-8"));
            // 输出文件
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> page = checkSetmealDao.selectByCondition(queryPageBean.getQueryString());
        List<Setmeal> setmeals = page.getResult();
        long total = page.getTotal();
        return  new PageResult(total,setmeals);
    }

    @Override
    public Setmeal findById(int id) {
        Setmeal setmeal = checkSetmealDao.findById(id);
        List<Integer> list = findGroupById(id);
        List<CheckGroup> checkGroups = new ArrayList<>();
        if (list!=null&&list.size()>0) {
            for (Integer integer : list) {
                CheckGroup checkGroup = checkGroupDao.findById(integer);
                checkGroups.add(checkGroup);
                List<Integer> itemList = checkGroupDao.findItemById(integer);
                List<CheckItem> checkItems = new ArrayList<>();
                for (Integer integer1 : itemList) {
                    CheckItem checkItem = checkItemDao.findById(integer1);
                    checkItems.add(checkItem);
                }
                checkGroup.setCheckItems(checkItems);
            }
        }
        setmeal.setCheckGroups(checkGroups);
        return setmeal;
    }

    @Override
    public List<Integer> findGroupById(int id) {
        return checkSetmealDao.findGroupById(id);
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        checkSetmealDao.edit(setmeal);
//      清理原有关系
        checkSetmealDao.deleteCheckGroup(setmeal.getId());
//      添加新增关系
        addGroupAndItem(setmeal.getId(),checkgroupIds);

    }

    @Override
    public void deleteById(int id) {
        checkSetmealDao.deleteCheckGroup(id);
        checkSetmealDao.deleteByIds(id);
    }

    @Override
    public List<Setmeal> findAll() {

        return checkSetmealDao.findAll();

    }

    private void addGroupAndItem(int id,Integer[] checkgroupIds){

        if (checkgroupIds!=null&&checkgroupIds.length>0){
           for (Integer checkgroupId : checkgroupIds) {
            Map<String, Integer> map = new HashMap<>();
            map.put("setmealId", id);
            map.put("groupId", checkgroupId);
            checkSetmealDao.addMealAndGroup(map);
           }
        }
    }

}
